/**
 * Created with JetBrains PhpStorm.
 * User: ekalinak
 * Date: 3.1.2014
 * Time: 8:18
 * To change this template use File | Settings | File Templates.
 */
chrome.omnibox.setDefaultSuggestion({
    'description' : 'Some default description'
});

chrome.omnibox.onInputStarted.addListener(function(){
    // Nothing to do, only for testing purposes
});
;
chrome.omnibox.onInputChanged.addListener(function(text, suggest){
    var allShortcuts = getShortcuts();
    var omniResults = [];
    var iterator = 0;

    if (text.length == 0 ){
        suggest(allShortcuts);
    }

    for ( var i = 0; i < allShortcuts.length; i++) {
            if (
                allShortcuts[i]['description'].indexOf(text) > 0 ||
                allShortcuts[i]['content'].indexOf(text) > 0 ||
                    allShortcuts[i]['description'] == text ||
                    allShortcuts[i]['content'] == text
                ) {
                omniResults[iterator] = allShortcuts[i];
                iterator++;
            }
    }

    suggest(omniResults);
});

chrome.omnibox.onInputEntered.addListener(function(text){
    var allShortcuts = getShortcuts()

    for ( var i = 0; i < allShortcuts.length; i++){
        if ( allShortcuts[i]['content'] == text){
            chrome.tabs.create({'url' : allShortcuts[i]['description'], active: true});
            break;
        }
    }
});

function getShortcuts () {
    var shortcuts = (localStorage.shortcuts) ? JSON.parse(localStorage.shortcuts) : {};
    var shortcutsArray = [];
    var iterator = 0;

    for (var i in shortcuts) {
        if ( shortcuts[i]['url']) {
            shortcutsArray[iterator] = {
                'content' : shortcuts[i]['shortcut'],
                'description' : shortcuts[i]['url']
            }
            iterator++;
        }
    }
    return shortcutsArray;
}